<template>
  <div id="app" v-if="isOnline">
    <div class="app-main">
      <div class="app-main-content">
        <breadcrumb-component :breadcrumArr="breadcrumArr" />
        <keep-alive>
          <router-view v-if="isKeepAlive && isRouterAlive" />
        </keep-alive>
        <router-view v-if="!isKeepAlive && isRouterAlive" />
      </div>
    </div>
  </div>
  <refresh v-else />
</template>

<script>
export default {
  name: 'App',
  provide() {
    // 父组件中通过provide来提供变量，在子组件中通过inject来注入变量。
    return {
      reload: this.reload
    };
  },
  computed: {
    isKeepAlive() {
      return this.$route.meta.keepAlive;
    },
    // 面包屑
    breadcrumArr() {
      return this.$route.meta.groupName;
    }
  },
  data() {
    return {
      isOnline: true, // 断网判断
      isRouterAlive: true // 控制视图是否显示的变量
    };
  },
  mounted() {
    // 获取当前网络状态
    this.navigatorOnline();
    // 监听网络连接状态
    window.addEventListener('online', this.handleOnline, false);
    window.addEventListener('offline', this.handleOnline, false);
    window.onpageshow = (event) => {
      if (event.persisted) window.location.reload();
    };
  },
  methods: {
    // 获取网络连接状态
    navigatorOnline() {
      this.handleOnline({ type: navigator.onLine ? 'online' : 'offline' });
    },
    // 监听网络连接状态
    handleOnline(event) {
      this.isOnline = event.type === 'online';
    },
    // 刷新视图
    reload() {
      this.isRouterAlive = false; // 先关闭
      this.$nextTick(() => {
        this.isRouterAlive = true; // 再打开
      });
    }
  },
  beforeDestroy() {
    // 清除监听 释放内存
    window.removeEventListener('online', this.handleOnline);
    window.removeEventListener('offline', this.handleOnline);
  }
};
</script>

<style lang="scss">
@import './styles/index.scss';
</style>
